import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        redirect: '/login',
    },
    {
        path: '/login',
        component: () =>
            import(/* webpackChunkName: "user" */ '../views/Login.vue'),
    },
    {
        path: '/register',
        component: () =>
            import(/* webpackChunkName: "user" */ '../views/Register.vue'),
    },
    {
        path: '/home',
        component: () =>
            import(/* webpackChunkName: "user" */ '../views/Home.vue'),
    },
    {
        path: '/mine',
        component: () =>
            import(/* webpackChunkName: "user" */ '../views/Mine.vue'),
    },
];

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes,
});

// 导航守卫
router.beforeEach((to, from, next) => {
    // 对于登录页面和注册页面，不需要登录才能操作，所以直接放行
    if (to.path === '/login' || to.path === '/register') return next();
    // 除了以上两个接口外，我都校验登录
    if (!window.sessionStorage.getItem('token')) return next('/login');
    // 有了就向下执行
    next();
});

export default router;
